import React, {useEffect, useState} from 'react';
import {Avatar, Flex, Typography} from 'antd';
import { RobotOutlined, UserOutlined } from '@ant-design/icons';
import ReactMarkdown from 'react-markdown';
import SyntaxHighlighter from 'react-syntax-highlighter';
import { atomOneDark } from 'react-syntax-highlighter/dist/esm/styles/hljs';
import remarkGfm from 'remark-gfm';
import rehypeRaw from 'rehype-raw';
import type { Message } from '../ChatMessageList';
import type { BubbleProps } from '@ant-design/x';
import 'github-markdown-css';
import { useParams } from '@umijs/max';
import './index.less';
import {Bubble} from "@ant-design/x";
import markdownit from 'markdown-it';
import hljs from 'highlight.js'
const { Text } = Typography;
import 'highlight.js/styles/a11y-light.css'

interface ChatMessageItemProps {
  message: Message;
  parent?: Message;
  onMessageChange?: () => void;
  onUpdate:
    | ((messageId: string, agentId: string, content: string, status: string) => void)
    | undefined;
  agent: any;
}

interface CodeComponentProps {
  children: React.ReactNode;
  className?: string;
  node?: any;
  inline?: boolean;
}

const md = markdownit({
  html: true,
  breaks: true,
  highlight: function (str, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return '<pre><code class="hljs">' +
          hljs.highlight(str, { language: lang, ignoreIllegals: true }).value +
          '</code></pre>';
      } catch (__) {}
    }

    return '<pre><code class="hljs">' + md.utils.escapeHtml(str) + '</code></pre>';
  }
});

// 为表格添加自定义类
md.renderer.rules.table_open = () => '<table class="custom-table">';
md.renderer.rules.th_open = () => '<th class="custom-th">';
md.renderer.rules.td_open = () => '<td class="custom-td">';
const renderMarkdown: BubbleProps['messageRender'] = (content) => (
  <Typography>
    {/* biome-ignore lint/security/noDangerouslySetInnerHtml: used in demo */}
    <div dangerouslySetInnerHTML={{ __html: md.render(content) }} />
  </Typography>
);

const renderText: BubbleProps['messageRender'] = (content) => (
  <Typography>
    {/* biome-ignore lint/security/noDangerouslySetInnerHtml: used in demo */}
    <div dangerouslySetInnerHTML={{ __html: content }} />
  </Typography>
);


const ChatMessageItem: React.FC<ChatMessageItemProps> = ({
  message,
  parent,
  onMessageChange,
  onUpdate,
  agent,
  sessionId
}) => {
  // Render message content based on content type
  const [loading, setLoading] = useState(false)
  useEffect(() => {
    console.log('check the message status', message, parent, agent);
    if (message.role === 'user') {
      return;
    }
    if (!message.parent) {
      return;
    }
    if (loading) {
      console.log('message is loading', loading, message.messageId)
      return;
    }
    if (message.status?.toLowerCase() === 'init' && message.role === 'assistant' && agent) {
      setLoading(true);
      const fetchData = async () => {
        const response = await fetch('http://localhost:8080/api/' + agent.url, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            messageId: message?.messageId,
            agentId: agent.id,
            sessionId: sessionId,
          }),
        });

        const reader = response.body?.getReader();
        const decoder = new TextDecoder();

        if (!reader) {
          throw new Error('Failed to initialize stream reader');
        }

        while (true) {
          const { done, value } = await reader.read();
          if (done) {
            message.status = 'complete';
            if (message.parent) {
              message.parent.status = 'complete';
            }
            setLoading(false);
            break;
          }

          const chunks = decoder.decode(value, { stream: true });
          console.log(chunks);
          if (chunks) {
            chunks.split('\n\n').forEach((chunk) => {
              if (chunk) {
                let parse = JSON.parse(chunk);
                parse?.choices?.forEach((item) => {
                  onUpdate(message.messageId, agent.id, item.delta.content, 'wip');
                  if (message.parent) {
                    //updateMessageId(message.parent.message_id, parse.parentId);
                  }
                  if (item.delta.content) {
                    // setContent((prevState) => {
                    //   return prevState + item.delta.content;
                    // });
                    onMessageChange();
                  }
                });
              }
            });
          }
          // setContent((prevState) => {
          //   return prevState + chunk;
          // });
        }
      };

      try {
        fetchData();
      } catch (error) {
        onUpdate(message.messageId, '\n系统异常\n', 'wip');
        onMessageChange();
      }
    }
  }, [message]);

  const renderMessageContent = () => {
    switch (message.contentType) {
      case 'image':
        return <img width={200} src={message.content} alt="AI generated" />;

      case 'markdown':
        return (
          <ReactMarkdown
            remarkPlugins={[remarkGfm]}
            rehypePlugins={[rehypeRaw]}
            components={{
              code: ({ className, children, inline }: CodeComponentProps) => {
                const match = /language-(\w+)/.exec(className || '');
                return !inline && match ? (
                  <SyntaxHighlighter style={atomOneDark} language={match[1]} PreTag="div">
                    {String(children).replace(/\n$/, '')}
                  </SyntaxHighlighter>
                ) : (
                  <code className={className}>{children}</code>
                );
              },
              table: ({ node, ...props }) => <table {...props} className="custom-table" />,
              th: ({ node, ...props }) => <th {...props} className="custom-th" />,
              td: ({ node, ...props }) => <td {...props} className="custom-td" />,
            }}
          >
            {message.content}
          </ReactMarkdown>
        );

      default:
        return <Text style={{ whiteSpace: 'pre-wrap' }}>{message.content}</Text>;
    }
  };

  return (
    <Flex gap="middle" vertical>
      <Bubble
        placement={message.role === 'user'?'end':'start'}
        content={message.content}
        messageRender={message.role === 'user'? renderText : renderMarkdown}
        avatar={{ icon: message.role === 'user' ? <UserOutlined /> : <RobotOutlined />}}
      />
    </Flex>
    // <div
    //   style={{
    //     maxWidth: '90%',
    //     padding: 12,
    //     borderRadius: 8,
    //     background: message.role === 'user' ? '#1890ff' : '#f0f0f0',
    //     color: message.role === 'user' ? 'white' : 'black',
    //   }}
    // >
    //   <div style={{ display: 'flex', alignItems: 'center', marginBottom: 8 }}>
    //     <Avatar
    //       icon={message.role === 'user' ? <UserOutlined /> : <RobotOutlined />}
    //       style={{
    //         background: message.role === 'user' ? '#fff' : '#1890ff',
    //         color: message.role === 'user' ? '#1890ff' : '#fff',
    //         marginRight: 8,
    //       }}
    //     />
    //     <Text strong style={{ color: message.role === 'user' ? '#fff' : '#000' }}>
    //       {message.role === 'user' ? 'You' : agent?.name}
    //     </Text>
    //   </div>
    //
    //   <div style={{ marginTop: 8 }}>{renderMessageContent()}</div>
    //
    //   {message.timestamp && (
    //     <div style={{ marginTop: 8, textAlign: 'right' }}>
    //       <Text
    //         type="secondary"
    //         style={{ fontSize: 12, color: message.role === 'user' ? '#fff' : '#666' }}
    //       >
    //         {new Date(message.timestamp).toLocaleTimeString()}
    //       </Text>
    //     </div>
    //   )}
    // </div>
  );
};

export default ChatMessageItem;
